import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import SSOLoginView from '../views/SSOLoginView.vue'
import Index from '../views/Index.vue'
import { isSSORwork } from '../utils/config'
import { useAuthStore } from '../stores/auth'
console.log('xxxxxxxxxxxxxxxx routerBasePath', routerBasePath())

localStorage.setItem('routerBasePath', routerBasePath())

const router = createRouter({
  history: createWebHistory(routerBasePath()),
  routes: [
    {
      path: '/',
      redirect: '/homeView',
      meta: { requiresAuth: true }
    },
    {
      path: '/index',
      component: () => import('@/views/Index.vue'),
      children: [
        {
          path: '/homeView',
          name: 'homeView',
          meta: { requiresAuth: true },
          component: () => import('@/views/HomeView.vue')
        },
        {
          path: '/agentSquare',
          name: 'agentSquare',
          meta: { requiresAuth: true },
          component: () => import('../views/AgentSquare.vue')
        }
      ]
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('../views/AboutView.vue')
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView
    }
  ]
})

router.beforeEach(async (to, from, next) => {
  // 检查是否需要登录才能访问
  const requiresAuth = to.matched.some((record) => record.meta.requiresAuth)
  const authStore = useAuthStore()

  // 如果需要登录并且用户未登录，则重定向到登录页面
  if (requiresAuth && !authStore.isLoggedIn.value) {
    // 使用 encodeURIComponent 对 fullPath 进行编码
    const encodedFullPath = encodeURIComponent(to.fullPath)
    next({ name: 'login', query: { redirect: encodedFullPath } })
  } else {
    next()
  }
})

function routerBasePath(): string {
  const seacondPaths = ['portal', 'crpower']
  // 分割路径以获取目录部分
  const parts = window.location.pathname.split('/')

  // 如果路径部分少于2个（例如，没有二级目录），则返回false
  if (parts.length < 2) {
    return '/'
  }

  // 获取二级目录名称
  const secondDirectory = parts[1] // 假设路径以 '/' 开头，并且我们想要的是第二个部分

  // 检查二级目录是否在允许的路径中
  if (seacondPaths.includes(secondDirectory)) {
    return `/${secondDirectory}/`
  }
  return '/'
}

export default router
